package com.rc.web.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.rc.pojo.dto.address.AddressAddDTO;
import com.rc.pojo.dto.address.AddressUpdateDTO;
import com.rc.pojo.po.Address;
import com.rc.pojo.vo.address.AddressVO;
import com.rc.web.converter.AddressConverter;
import com.rc.web.mapper.AddressMapper;
import com.rc.web.service.AddressService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户地址表 服务层实现。
 * 提供用户地址相关的业务逻辑实现
 */
@Service
@RequiredArgsConstructor
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService {
    // 地址转换器
    private final AddressConverter addressConverter;

    /**
     * 获取地址列表
     * @return 地址VO列表
     */
    @Override
    public List<AddressVO> getList() {
        List<Address> addresses = this.list();
        return addresses.stream()
                .map(addressConverter::toVO)
                .toList();
    }

    /**
     * 根据ID删除地址
     * @param id 地址ID
     */
    @Override
    public void deleteOneById(Long id) {
        this.removeById(id);
    }

    /**
     * 添加地址
     * @param addressAddDTO 地址添加DTO
     */
    @Override
    public void add(AddressAddDTO addressAddDTO) {
        Address address = addressConverter.addDTO2PO(addressAddDTO);
        this.save(address);
        //如果地址是默认则把用户其他地址设为非默认
        if (address.getIsDefault()){
            mapper.updateNoDefault(address.getId());
        }
    }

    /**
     * 更新地址信息
     * @param dto 地址更新DTO
     */
    @Override
    public void updateOneById(AddressUpdateDTO dto) {
        var address = addressConverter.updateDTO2PO(dto);
        address.setConId(StpUtil.getLoginIdAsLong());

        var success = this.updateById(address);
        //如果地址是默认且存在则把用户其他地址设为非默认
        if (address.getIsDefault() && success){
            mapper.updateNoDefault(address.getId());
        }
    }

    /**
     * 根据ID获取地址信息
     * @param id 地址ID
     * @return 地址VO
     */
    @Override
    public AddressVO getOneById(Long id) {
        var address = mapper.selectOneById(id);
        return addressConverter.toVO(address);
    }
}
